import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @License: (C) Copyright 2013-2022
 * @Contact: abcque@outlook.com
 * @IDE: IntelliJ IDEA
 * @Encoding: utf-8
 * @Project: st2214st2215
 * @Package: PACKAGE_NAME
 * @File: TCPCopyFileServer.java
 * @Time: 2023/5/23 14:34
 * @Author: abcque
 * @Description:
 * @Modifier:
 * @ModifyDate:
 * @ModifyRemark:
 */
public class TCPCopyFileServer {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("文件传输服务器已经开启，等待客户端进行连接");
            Socket server = null;

            server = serverSocket.accept();
            System.out.println("客户端与服务器已经连接");

            // 打开输入流
            InputStream inputStream = server.getInputStream();
            byte[] bytes = new byte[8192];
            // 接收文件名
            int length = inputStream.read(bytes);
            String fileName = new String(bytes, 0, length);
            System.out.println("来自客户端的文件名：" + fileName);
            // 接收文件大小
            length = inputStream.read(bytes);
            long size = Long.parseLong(new String(bytes, 0, length));
            System.out.println("文件大小：" + size);

            long receiveLength = 0;
            FileOutputStream fileOutputStream = new FileOutputStream("copy " + fileName);

            while ((length = inputStream.read(bytes))!= -1){
                fileOutputStream.write(bytes, 0, length);
                receiveLength += length;
                if (receiveLength == size){
                    break;
                }
            }

            fileOutputStream.close();
            System.out.println("文件接收完毕");
            // 打开输出流
            OutputStream outputStream = server.getOutputStream();
            String info = "发送成功";
            outputStream.write(info.getBytes());
            outputStream.close();

            inputStream.close();
            server.close();
            serverSocket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
